package com.bjy.qa.agent.tester.handlers;

import com.alibaba.fastjson.JSONObject;
import com.bjy.qa.agent.enumtype.ConditionEnum;
import com.bjy.qa.agent.enumtype.RunStatus;
import com.bjy.qa.agent.model.HandleDes;
import com.bjy.qa.agent.tester.RunStepThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * for 步骤
 */
@Component
public class ForHandler implements StepHandler {
    @Autowired
    private StepHandlers stepHandlers;

    /**
     * for 步骤
     * @param stepJSON 步骤 json
     * @param handleDes HandleDes 模型
     * @param thread RunStepThread
     * @return
     * @throws Throwable
     */
    @Override
    public HandleDes runStep(JSONObject stepJSON, HandleDes handleDes, RunStepThread thread) throws Throwable {
        if (thread.isStopped()) {
            return null;
        }
        handleDes.clear();

        // 取出 for 下的步骤集合
        JSONObject conditionStep = stepJSON.getJSONObject("step");
        List<JSONObject> steps = conditionStep.getJSONArray("childSteps").toJavaList(JSONObject.class);

        String stepDesc = conditionStep.getString("desc"); // 步骤描述

        // 读取循环次数
        int time;
        try {
            time = conditionStep.getIntValue("extra1");
        } catch (Exception e) {
            thread.getLogTool().sendStepLog(RunStatus.ERROR, stepDesc, "「for」循环执行失败，循环次数非数值类型！", "");
            handleDes.setE(e);
            return handleDes;
        }

        // 执行循环步骤
        thread.getLogTool().sendStepLog(RunStatus.PASSED, stepDesc, "开始执行「for」循环步骤" , "共循环 " + time + " 次");
        for (int i=1; i<=time; i++) {
            if (handleDes.getE() != null || thread.isStopped()) {
                break;
            }
            // 取出 for 下所属的步骤丢给 stepHandlers 处理
            thread.getLogTool().sendStepLog(RunStatus.PASSED, stepDesc, "第「" + i + "」次循环", "");
            for (JSONObject step : steps) {
                stepHandlers.runStep(handlerPublicStep(step), handleDes, thread);
            }
        }
        if (handleDes.getE() == null) {
            thread.getLogTool().sendStepLog(RunStatus.PASSED, stepDesc, "「for」循环步骤执行完毕", "");
        }else {
            thread.getLogTool().sendStepLog(RunStatus.WARN, stepDesc, "「for」步骤执行失败，循环结束", "");
        }
        if (thread.isStopped()) {
            thread.getLogTool().sendStepLog(RunStatus.WARN, stepDesc, "「for」被强制中断", "");
        }

        // 不满足条件则返回
        return handleDes;
    }

    /**
     * 获取步骤类型
     * @return
     */
    @Override
    public ConditionEnum getCondition() {
        return ConditionEnum.FOR;
    }
}
